package com.codeant.bikeindicatorapplication.tools;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

//Google推荐使用DataStore（alpha，Kotlin） 替换 SharedPreferences
public class SharedPreferencesHelper {
    
    Context myContext;
    
    public void initSP(Context context){
        this.myContext = context;
    }

    //保存bool型数据
    public void saveSP_boolean(String PREFS_NAME, String s, Boolean b){
        SharedPreferences mySP = myContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySP.edit();//获取Editor
        //得到Editor后，写入需要保存的数据
        editor.putBoolean(s, b);
        editor.apply();//提交修改
        Log.i("SPHelper", "保存成功");
    }

    //读取bool型数据
    public boolean getSP_boolean(String PREFS_NAME, String s, boolean default_b){
        SharedPreferences mySP = myContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        boolean result = mySP.getBoolean(s, default_b);//读取对应数据
        Log.i("SPHelper", "读取SharedPre:"+ PREFS_NAME+ " "+ s);
        return result;
    }

    //保存float型数据
    public void saveSP_float(String PREFS_NAME, String s, float f){
        SharedPreferences mySP = myContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySP.edit();//获取Editor
        //得到Editor后，写入需要保存的数据
        editor.putFloat(s, f);
        editor.apply();//提交修改
        Log.i("SPHelper", "保存成功");
    }

    //读取float型数据
    public float getSP_float(String PREFS_NAME, String s, String default_s){
        SharedPreferences mySP = myContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        float result = mySP.getFloat(s, Float.parseFloat(default_s));//读取对应数据
        Log.i("SPHelper", "读取SharedPre:"+ PREFS_NAME+ " "+ s);
        return result;
    }

    //移除
    public void removeSP(String PREFS_NAME){
        SharedPreferences mySP = myContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySP.edit();//获取Editor
        editor.remove("age");
        editor.apply();
        Log.i("SPHelper", "移除"+ PREFS_NAME);
    }

    //清空
    public void clearSP(String PREFS_NAME){
        SharedPreferences mySP = myContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySP.edit();//获取Editor
        editor.clear();
        editor.apply();
        Log.i("SPHelper", "清空SharedPre:"+PREFS_NAME);
    }
}
